<template>
  <view class="container">
    <Loading :show="isLoading" />
    <!-- 用户积分信息 -->
    <view class="points-info">
      <text class="points-label">当前积分</text>
      <text class="points-value">{{ userPoints }}</text>
    </view>

    <!-- 兑换列表 -->
    <view class="exchange-list">
      <view v-if="exchangeList.length === 0" class="empty-state">
        <text class="empty-text">暂无可兑换的优惠券</text>
      </view>

      <view
        v-else
        v-for="item in exchangeList"
        :key="item.id"
        class="exchange-item"
      >
        <view class="exchange-header">
          <text class="coupon-name">{{ item.couponName }}</text>
          <text class="exchange-status" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </text>
        </view>

        <view class="exchange-content">
          <view class="points-required">
            <text class="points-text">{{ item.points }}</text>
            <text class="points-unit">积分</text>
          </view>

          <view class="exchange-info">
            <view class="info-item">
              <text class="info-label">兑换限制：</text>
              <text class="info-value">{{ item.exchangeLimit === -1 ? '不限次数' : `每人限兑${item.exchangeLimit}次` }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">有效期：</text>
              <text class="info-value">{{ formatTime(item.startTime) }} - {{ formatTime(item.endTime) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">优惠券类型：</text>
              <text class="info-value">{{ getCouponTypeText(item.coupon?.type) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">优惠内容：</text>
              <text class="info-value highlight">{{ getCouponValueText(item.coupon) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">使用范围：</text>
              <text class="info-value">{{ getUseScopeText(item.coupon?.useScope) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">规则说明：</text>
              <text class="info-value">{{ item.description }}</text>
            </view>
          </view>
        </view>

        <view class="exchange-footer">
          <button
            :class="'exchange-btn' + (!canExchange(item) ? ' disabled' : '')"
            :disabled="!canExchange(item)"
            @click="handleExchange(item)"
          >
            {{ getExchangeBtnText(item) }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import http from "@/utils/request";
import { getUserAccount } from "@/api/user";
import Loading from "@/components/Loading.vue";
import { getExchangeRuleList } from "@/api/coupon/exchange";
import { getUserCouponList } from "@/api/coupon/user";
import { exchangeCoupon } from "@/api/coupon/exchange";

// 定义接口
interface Coupon {
  id: number;
  name: string;
  code: string;
  type: number;
  discount: string;
  minPoint: string;
  useScope: number;
  scopeId: string;
  startTime: string;
  endTime: string;
  totalCount: number;
  usedCount: number;
  receiveCount: number;
  status: number;
}

interface ExchangeRule {
  id: number;
  couponId: number;
  couponName: string;
  points: number;
  exchangeLimit: number;
  startTime: string;
  endTime: string;
  status: number;
  description: string;
  coupon?: Coupon;
}

// 加载状态
const isLoading = ref(false);

// 用户积分
const userPoints = ref(0);

// 兑换列表
const exchangeList = ref<ExchangeRule[]>([]);

// 用户已领取的优惠券数量
const userCouponCount = ref<{ [key: number]: number }>({});

const userInfo = ref<any>(null);

// 初始化用户信息
const initUserInfo = () => {
  const storedUserInfo = uni.getStorageSync('userInfo')
  if (storedUserInfo) {
    userInfo.value = storedUserInfo
  }
}

// 获取用户已领取的优惠券数量
const getUserCouponCount = async () => {
  try {
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo) return;

    const res = await getUserCouponList({
      userId: userInfo.id,
      pageNum: 1,
      pageSize: 10
    });
    
    if (res.code === 200 && res.rows) {
      // 统计每个优惠券的领取次数
      const countMap: { [key: number]: number } = {};
      res.rows.forEach((item: any) => {
        if (item.couponId) {
          countMap[item.couponId] = (countMap[item.couponId] || 0) + 1;
        }
      });
      userCouponCount.value = countMap;
      console.log(countMap)
    
    }
  } catch (error) {
    console.error("获取用户优惠券数量失败：", error);
  }
};

// 获取兑换列表
const getList = async () => {
  try {
    const res = await getExchangeRuleList()
    if (res.code === 200) {
      // 预处理，保证exchangeLimit为number
      const rows = res.rows.map((item: any) => ({
        ...item,
        exchangeLimit: typeof item.exchangeLimit === 'number' ? item.exchangeLimit : (item.exchangeLimit === undefined ? -1 : Number(item.exchangeLimit))
      }))
      // 对列表进行排序
      exchangeList.value = rows.sort((a: any, b: any) => {
        const aCount = userCouponCount.value[a.id] || 0
        const bCount = userCouponCount.value[b.id] || 0
        // 判断是否可兑换，-1视为永远可兑换
        const aCanExchange = a.exchangeLimit === -1 ? true : aCount < a.exchangeLimit
        const bCanExchange = b.exchangeLimit === -1 ? true : bCount < b.exchangeLimit
        if (aCanExchange !== bCanExchange) {
          return aCanExchange ? -1 : 1
        }
        return a.points - b.points
      })
    }
  } catch (error) {
    console.error('获取兑换列表失败：', error)
  }
}

// 获取用户积分
const getUserPoints = async () => {
  try {
    isLoading.value = true;
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取最新的积分数据
    const res = await getUserAccount(userInfo.id);
    if (res.code === 200 && res.data) {
      const newPoints = res.data.points || 0;
      // 如果积分有变化，更新本地存储
      if (newPoints !== userInfo.points) {
        userInfo.points = newPoints;
        uni.setStorageSync('userInfo', userInfo);
      }
      userPoints.value = newPoints;
    }
  } catch (error) {
    console.error("获取积分失败：", error);
    // 如果获取失败，使用本地存储的积分
    userPoints.value = userInfo.points || 0;
    uni.showToast({
      title: '获取积分失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 获取兑换按钮文本
const getExchangeBtnText = (item: any) => {
  const userInfo = uni.getStorageSync('userInfo')
  if (!userInfo) return '请先登录'
  if (userInfo.points < item.points) {
    return '积分不足'
  }
  const userCount = userCouponCount.value[item.id] || 0
  if (item.exchangeLimit !== -1 && userCount >= item.exchangeLimit) {
    return '已达上限'
  }
  return '立即兑换'
}

// 判断是否可兑换
const canExchange = (item: any) => {
  if (!userInfo.value) return false
  if (userInfo.value.points < item.points) {
    return false
  }
  const userCount = userCouponCount.value[item.id] || 0
  if (item.exchangeLimit === -1) return true
  return userCount < item.exchangeLimit
}

// 处理兑换
const handleExchange = async (item: ExchangeRule) => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (!userInfo) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 检查积分是否足够
    if (userInfo.points < item.points) {
      uni.showToast({
        title: '积分不足',
        icon: 'none'
      })
      return
    }

    // 检查是否达到兑换上限
    const userCount = userCouponCount.value[item.id] || 0
    if (item.exchangeLimit !== -1 && userCount >= item.exchangeLimit) {
      uni.showToast({
        title: '已达到兑换上限',
        icon: 'none'
      })
      return
    }

    // 格式化日期为 yyyy-MM-dd HH:mm:ss
    const formatDate = (date: Date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }

    // 计算兑换后的剩余积分
    const remainingPoints = userInfo.points - item.points

    // 构建兑换请求数据
    const exchangeData = {
      userId: userInfo.id,
      couponId: item.couponId,
      couponCode: item.coupon?.code || '',
      status: 0, // 未使用状态
      getType: 2, // 积分兑换
      getTime: formatDate(new Date()),
      expireTime: item.coupon?.endTime ? formatDate(new Date(item.coupon.endTime)) : null,
      points: remainingPoints // 使用计算后的剩余积分
    }

    const res = await exchangeCoupon(exchangeData)
    if (res.code === 200) {
      uni.showToast({
        title: '兑换成功',
        icon: 'success'
      })
      // 更新用户积分
      await getUserPoints()
      // 更新用户优惠券数量
      await getUserCouponCount()
      // 刷新兑换列表
      await getList()
    } else {
      uni.showToast({
        title: res.msg || '兑换失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('兑换失败：', error)
    uni.showToast({
      title: '兑换失败',
      icon: 'none'
    })
  }
}

// 获取优惠券类型文本
const getCouponTypeText = (type: number) => {
  const typeMap: { [key: number]: string } = {
    1: "满减券",
    2: "折扣券",
    3: "立减券"
  };
  return typeMap[type] || "未知类型";
};

// 获取优惠券值文本
const getCouponValueText = (coupon: any) => {
  if (!coupon) return "";
  switch (coupon.type) {
    case 1: // 满减券
      return `满${coupon.minPoint}减${coupon.discount}`;
    case 2: // 折扣券
      return `${Number(coupon.discount) * 10}折`;
    case 3: // 立减券
      return `立减${coupon.discount}`;
    default:
      return "";
  }
};

// 获取使用范围文本
const getUseScopeText = (scope: number) => {
  const scopeMap: { [key: number]: string } = {
    0: "全场通用",
    1: "指定品类",
    2: "指定商品"
  };
  return scopeMap[scope] || "未知范围";
};

// 获取状态样式
const getStatusClass = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: "status-disabled",
    1: "status-active",
    2: "status-ended",
  };
  return statusMap[status] || "";
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: "未启用",
    1: "可兑换",
    2: "已结束",
  };
  return statusMap[status] || "";
};

// 格式化时间
const formatTime = (time: string) => {
  return time.split(" ")[0];
};

// 初始化数据
onMounted(async () => {
  try {
    isLoading.value = true
    // 初始化用户信息
    initUserInfo()
    // 获取用户积分
    await getUserPoints()
    // 获取用户已领取的优惠券数量
    await getUserCouponCount()
    // 获取兑换列表
    await getList()
  } catch (error) {
    console.error('初始化数据失败：', error)
  } finally {
    isLoading.value = false
  }
})
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.points-info {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.points-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.points-value {
  font-size: 32px;
  color: #ff6b6b;
  font-weight: bold;
}

.exchange-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.exchange-item {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.exchange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.coupon-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.exchange-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 10px;
}

.status-disabled {
  background-color: #f0f0f0;
  color: #999;
}

.status-active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-ended {
  background-color: #f5f5f5;
  color: #999;
}

.exchange-content {
  margin-bottom: 15px;
}

.points-required {
  text-align: center;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fff5f5;
  border-radius: 8px;
}

.points-text {
  font-size: 24px;
  color: #ff6b6b;
  font-weight: bold;
}

.points-unit {
  font-size: 14px;
  color: #ff6b6b;
  margin-left: 4px;
}

.exchange-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  font-size: 14px;
  line-height: 1.5;
}

.info-label {
  color: #666;
  min-width: 80px;
}

.info-value {
  color: #333;
  flex: 1;
}

.info-value.highlight {
  color: #ff6b6b;
  font-weight: bold;
}

.exchange-footer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.exchange-btn {
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #ff6b6b;
  color: #ffffff;
  border-radius: 20px;
  font-size: 16px;
  border: none;
}

.exchange-btn.disabled {
  background-color: #f5f5f5;
  color: #999;
}
</style>
